﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using DAL;
using System.IO;
using System.Xml;
using System.Text;
using System.Data;
using System.Data.SqlClient;

public class wechatlink : IHttpHandler
{
    const string Token = "jqx";
    WeChatHelper WH = new WeChatHelper();
    WeChatDAL WD = new WeChatDAL();
    QXHelper QX = new QXHelper();
    public void ProcessRequest(HttpContext context)
    {

        if (HttpContext.Current.Request.HttpMethod.ToUpper() == "GET")
        {
            VerifyToken();
        }
        else if (HttpContext.Current.Request.HttpMethod.ToUpper() == "POST")
        {

            StreamReader str = new StreamReader(HttpContext.Current.Request.InputStream, System.Text.Encoding.UTF8);
            XmlDocument xml = new XmlDocument();
            xml.Load(str);
            string ToUserName = xml.SelectSingleNode("xml").SelectSingleNode("ToUserName").InnerText;
            string FromUserName = xml.SelectSingleNode("xml").SelectSingleNode("FromUserName").InnerText;
            string CreateTime = xml.SelectSingleNode("xml").SelectSingleNode("CreateTime").InnerText;
            string MsgType = xml.SelectSingleNode("xml").SelectSingleNode("MsgType").InnerText;
            string keywords = "";
            string Event = "";
            if (MsgType == "text")
            {
                //执行接收到文本的关键词
                keywords = xml.SelectSingleNode("xml").SelectSingleNode("Content").InnerText;
                HandleKeywords(FromUserName, ToUserName, keywords);
            }
            else if (MsgType == "voice")
            {
                //接收语音内容，执行同text
                keywords = xml.SelectSingleNode("xml").SelectSingleNode("Recognition").InnerText;
                keywords = keywords.Substring(0, keywords.Length - 1);
                HandleKeywords(FromUserName, ToUserName, keywords);
            }
            else if (MsgType == "event")
            {
                //接收关注事件，执行被关注后的操作
                Event = xml.SelectSingleNode("xml").SelectSingleNode("Event").InnerText;
                HandleKeywords(FromUserName, ToUserName, Event);
            }
            else if (MsgType == "image")
            {
                //接收的图片
                ResponseWrite(WH.xmlText(FromUserName, ToUserName, "哇！好漂亮的图片啊！这你也信。我根本没看见好嘛，也没记下它，等我有空了上后台去翻吧。"));
            }
            else if (MsgType == "video")
            {
                //接收的视频
                ResponseWrite(WH.xmlText(FromUserName, ToUserName, "发啥视频啊，老老实实打字，我压根没有记录视频信息，白发了，浪费流量了吧。"));
            }
            else if (MsgType == "shortvideo")
            {
                //接收的短视频
                ResponseWrite(WH.xmlText(FromUserName, ToUserName, "你给我发了短视频！但是，我懒得去调用它。我也懒得把它存到我的服务器。"));
            }
            else if (MsgType == "location")
            {
                //接收的位置信息
                string Location_X = xml.SelectSingleNode("xml").SelectSingleNode("Location_X").InnerText;
                string Location_Y = xml.SelectSingleNode("xml").SelectSingleNode("Location_Y").InnerText;
                ResponseWrite(WH.xmlText(FromUserName, ToUserName, "这是你的坐标[" + Location_X + "|" + Location_Y + "]，但是给我这个有啥用！！"));
            }
            else if (MsgType == "link")
            {
                //接收的链接信息
                string Url = xml.SelectSingleNode("xml").SelectSingleNode("Url").InnerText;
                if ("http://www.itbum.cn/" == Url || "http://www.itbum.cn" == Url || "http://itbum.cn" == Url || "http://itbum.cn/" == Url || "itbum.cn" == Url)
                {
                    ResponseWrite(WH.xmlText(FromUserName, ToUserName, "我想你是想访问我的网站，那么你可以 <a href='http://www.itbum.cn'>点击这里</a>。"));
                }
                else
                {
                    ResponseWrite(WH.xmlText(FromUserName, ToUserName, "你给我发了个链接，但是有什么用呢？你还是 <a href='http://www.itbum.cn'>点击这里</a> 浏览下我的网站吧。"));
                }
            }
            else
            {
                //其他类型的信息
                ResponseWrite(WH.xmlText(FromUserName, ToUserName, "这是个奇怪的事件，我也不知道为啥！！" + WD.jhy_wechat_handle_keywords_null_query()));

            }

        }


    }


    #region 关键词处理
    public void HandleKeywords(string FromUserName, string ToUserName, string Keywords)
    {
        string resultstr = "";
        if (Keywords.IndexOf("@") == 0)
        {
            string uid = "";
            if (FromUserName == "oLyGmv539VhJVWfid-VHhPlBa0Z4")
            {
                uid = "1";
            }
            else if (FromUserName== "oLyGmv-6OG_lbouXUZtnsBPdl2Ew")
            {
                uid = "3";
            }
            
            BabyDAL BD = new BabyDAL();
            if (uid != "")
            {
                BD.jhy_baby_notepad_add(Keywords.Substring(Keywords.IndexOf("@") + 1, Keywords.Length - 1), uid);
                resultstr = WH.xmlText(FromUserName, ToUserName, "<a href='http://www.itbum.cn/res/baby/notepad.html'>查看记事本</a>");
            }
            else
            {
                HandleKeywords(FromUserName, ToUserName, Keywords.Substring(Keywords.IndexOf("@") + 1, Keywords.Length - 1));
            }
            
           
            
        }
        //else if (Keywords.IndexOf("#")==0)
        //{

        //}
        else
        {
            DataTable dt = new DataTable();
            //检索关键词
            dt = WD.jhy_wechat_handle_keywords_query(Keywords);
            if (dt.Rows.Count > 0)
            {
                StringBuilder sbText = new StringBuilder();
                StringBuilder sbNews = new StringBuilder();
                int ArticleCount = 0;
                string kw_msgtype = dt.Rows[0]["kw_msgtype_p"].ToString();
                if (kw_msgtype == "text")
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        sbText.Append(Microsoft.JScript.GlobalObject.unescape(dr["kw_text_content"].ToString()) + "\n");
                    }
                    resultstr = WH.xmlText(FromUserName, ToUserName, sbText.ToString());
                }
                else if (kw_msgtype == "news")
                {
                    ArticleCount = dt.Rows.Count;
                    foreach (DataRow dr in dt.Rows)
                    {
                        sbNews.Append(WH.xmlItem(dr["kw_news_title"].ToString(), dr["kw_news_description"].ToString(), dr["kw_news_picurl"].ToString(), dr["kw_news_url"].ToString()));
                    }
                    resultstr = WH.xmlNews(FromUserName, ToUserName, ArticleCount.ToString(), sbNews.ToString());
                }
            }
            else//如果关键词不存在，则检索文章
            {
                //增加文章检索
                if (WD.jhy_wechat_handle_article_query(Keywords) != "0")
                {
                    resultstr = WH.xmlNews(FromUserName, ToUserName, "1", WH.xmlItem("查看“" + Keywords + "”相关文章", "点击进入查看查询结果", "http://www.itbum.cn/images/qx.jpg", "http://www.itbum.cn?art_title=" + Keywords));
                }
                else
                {
                    resultstr = WH.xmlText(FromUserName, ToUserName, WD.jhy_wechat_handle_keywords_null_query());
                }
            }
            
        }
        //resultstr = WH.xmlText(FromUserName, ToUserName, "<a href='http://www.itbum.cn'>打开网站</a>");
        //返回数据
        ResponseWrite(resultstr);

    }
    #endregion

    #region 用来返回数据
    private void ResponseWrite(string resultstr)
    {
        HttpContext.Current.Response.ContentType = "text/xml";
        HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
        HttpContext.Current.Response.Write(resultstr);
        HttpContext.Current.Response.End();
    }
    #endregion

    #region token验证
    private void VerifyToken()
    {
        string echoStr = HttpContext.Current.Request.QueryString["echoStr"].ToString();
        string signature = HttpContext.Current.Request.QueryString["signature"].ToString();
        string timestamp = HttpContext.Current.Request.QueryString["timestamp"].ToString();
        string nonce = HttpContext.Current.Request.QueryString["nonce"].ToString();
        bool b = WH.verifytoken(Token, echoStr, signature, timestamp, nonce);
        if (b)
        {
            HttpContext.Current.Response.Write(echoStr);
            HttpContext.Current.Response.End();
        }
    }
    #endregion


    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}